import Konva from "konva";


function VGKonva(s = "container") {
  let container = s

  let _this = this;
  this.isNext = false; //是否绘制完背景
  this.ischangeLanguage = false; //是否允许替换
  let strID = container + '123';
  let isFilters = false;
  //定义一个工具类 放一些内部操作重用
  let util = {
    addDraw: (a, fn) => {
      this.layer.add(a)
      if (fn) {
        fn(this.layer)
      } else {
        this.layer.draw()
      }
      return this.layer
    }
  }
  //初始化某些参数
  this.init = () => {
    this.Stagewidth = $('#' + container).width();
    this.Stageheight = $('#' + container).height();
    this.config()
  }

  this.config = (obj = {}) => {
    this.BGresize = true //是否自适应
  }
  this.init();
  //绘制容器 layer
  this.drawLayer = (img) => {
    // console.log(img)
    $('#' + container).append("<div id='" + strID + "'></div>")
    // $('#'+container).width(Stagewidth)
    // console.log(this.Stagewidth, this.Stageheight)
    this.stage = new Konva.Stage({
      container: strID,
      width: this.Stagewidth,
      height: this.Stageheight,
    });
    this.layer = new Konva.Layer();
    this.stage.add(this.layer);
  }

  //绘制背景
  this.drawCanvasBG = (imageUrl) => {
    if (this.isNext) {
      isFilters?this.removeFilters():isFilters;
      //this.layer.find("Image").remove() //直接移除所有的图层 后面记得更改
      this.stage.remove()
      this.init();
    }
    let img2 = new Image();
    img2.src = imageUrl;
    let imgload = new Promise((resolve, reject) => {
      img2.onload = () => {
        // debugger
        //绘制画布
        this.isNext = true
        let objop //画布的绘制参数
        //是否去改变画布大小
        console.log(this.stage)
        if (this.BGresize & img2.width > this.Stagewidth) {
          // if (this.Stageheight >= img2.height && this.Stagewidth >= img2.width) {
          //   this.Stagewidth = img2.width;
          //   this.Stageheight = img2.height
          // }
          objop = this.imgconfig(img2, { id: "BG" });

          this.Stageheight = img2.height * (this.Stagewidth / img2.width)
          img2.width = this.Stagewidth
          // if (img2.height > this.Stageheight) {
          //   this.Stagewidth = img2.width * (img2.height / this.Stageheight)
          // }
          objop = this.imgconfig(img2, { width: this.Stagewidth, height: this.Stageheight, id: "BG" });
        } else {
          this.Stagewidth = img2.width;
          this.Stageheight = img2.height;
          objop = this.imgconfig(img2, { id: "BG" });
        }
       
        // this.Stagewidth = img2.width;
        // this.Stageheight = img2.height;
        // objop = this.imgconfig(img2, { id: "BG" });
        this.drawLayer(img2)

        let kImage2 = new Konva.Image(objop);
        // console.log(objop)
        //添加到层
        kImage2.setZIndex(0)
        util.addDraw(kImage2)
        resolve(kImage2);
      }
      img2.onerror = () => {
        reject(new Error('Could not load image '));
      }
    })

    return imgload
  }

  //返回一个img的配置
  this.imgconfig = (img, obj = {}, location = "left") => {
    //console.log(img)
    let a = {
      image: img,
      x: 0,
      y: 0,
      width: img.width,
      height: img.height,
    }
    a = Object.assign(a, obj)
    switch (location) {
    case "right":
      a.x = this.Stagewidth - a.width,
      a.y = 0;
      break;
    case "bottomCenter":
      a.x = (this.Stagewidth / 2) - (a.width / 2),
      a.y = (this.Stageheight - a.height)-47;
      break;
    case "bottomRight":
      a.x = (this.Stagewidth - a.width)-10,
      a.y = (this.Stageheight - a.height)-10;
      break;
    default:
      a.x = 0;
      a.y = 0;
      break
    }
    //console.log(location)
    return a
  }

  // location hasNode是否需要拖拽框 maxSize 最大比例  Osacle 缩放比例
  this.drawCanvas = (imageUrl, id = "img", location = "left", hasNode = true,maxSize=0.9,Osacle=1) => {
    let img2 = new Image();
    img2.src = imageUrl;
    let imgload = new Promise((resolve, reject) => {
      img2.onload = () => {
        img2.height= img2.height*Osacle
        img2.width= img2.width*Osacle
        let sacle = this.Stagewidth/img2.width;
        // console.log(sacle)
        
        let width = img2.width > this.Stagewidth*maxSize ? this.Stagewidth*maxSize : img2.width;
        let height = img2.width > this.Stagewidth*maxSize ? img2.height*sacle*maxSize : img2.height;
        let kImage2 = new Konva.Image(this.imgconfig(img2, { draggable: hasNode, id: id, width: width, height: height }, location));
        //添加到层
        this.layer.add(kImage2);
        if(hasNode){
          let kImage2c = new Konva.Transformer({
            nodes: [kImage2],
            centeredScaling: false,
          });
          util.addDraw(kImage2c);
          resolve(kImage2, kImage2c);
        }
        util.addDraw(kImage2);
        resolve(kImage2);
      }
      img2.onerror = () => {
        reject(new Error('Could not load image '));
      }
    })
    this.ischangeLanguage = true;
    return imgload;
  }
  this.transformershow = true; //是否展示拖拽框控件
  this.toggleTransformer = () => {
    // if(this.isFilters){
    //   this.layer.clearCache()
    // }
    this.transformershow ? this.layer.find("Transformer").hide() : this.layer.find("Transformer").show();
    this.transformershow = !this.transformershow;
    this.layer.draw()
  }
  this.hideTransformer = () =>{
    if(!this.transformershow){
      return false
    }
    this.layer.find("Transformer").hide()
    this.transformershow = false;
  }
  this.showTransformer = () =>{
    if(this.transformershow){
      return false
    }
    this.layer.find("Transformer").show()
    this.transformershow = true;
  }
  //更换语言时候更换图片
  this.changeLanguageImage = (id, src) => {
    if (!id || !src) { return false }
    let as = this.layer.find("#" + id)
    let img = new Image();
    img.src = src;
    img.onload = () => {  
      as.image(img)    
      this.layer.draw()
    }
  }
  //设置滤镜
  this.filters = (type="RGB") => {
    if(this.isFilters){
      this.removeFilters ()
    }
    this.hideTransformer()
    let node = this.layer;
    node.cache();
    switch (type) {
    case "RGB":
      node.filters([Konva.Filters.RGBA]);
      node.blue(0);
      node.green(0);
      node.red(0);
      node.alpha(0.1);
      break;
    case "Mask":
      node.filters([Konva.Filters.Mask]);
      node.threshold(0);
      break;
    case "HSV":
      node.filters([Konva.Filters.HSV]);
      node.value(200);
      break;
    case "Invert":
      node.cache();
      node.filters([Konva.Filters.Invert]);
      break;
    default:
      break;
    }
    this.isFilters=true;
    this.layer.draw()
    // debugger
  }
  this.filtersUpdata = (reg,opt={}) => {
    switch (reg) {
    case "RGB":
      this.layer.blue(opt.blue);
      this.layer.green(opt.green);
      this.layer.red(opt.red);  
      this.layer.alpha(opt.alpha);        
      break;
    case "Mask":
      opt.threshold = Number(opt.threshold)
      this.layer.threshold(opt.threshold);
      console.log(1)
      break
    default:
      break;
    }
    this.layer.draw()
  }
  this.removeFilters = () => {
    this.layer.clearCache()
    this.layer.filters([])
    this.isFilters=false
    this.showTransformer()
  }
  this.removeBG = () => {
    this.layer.find("#BG").remove()
    // this.layer.draw()
  }
  //获取背景的base64
  this.getBGData = ()=>{
    return  this.layer.find("#BG")[0].toDataURL()
  }
}

export default VGKonva